import struct
import random
import optparse

# generate the SCC web graph

def printwebgraph(filename):
    totalnode = 0
    binfile = open(filename,'rb')
    intsize = struct.calcsize('i')

    while 1:
        data = binfile.read(intsize)
        if data == '':
            break
        src = struct.unpack('i',data)[0]
        print '>',src,
        totalnode += 1

        data = binfile.read(intsize)
        if data == '':
            break
        outdegree = struct.unpack('i',data)[0]
        print '|',outdegree,'|',
        
        for i in range(outdegree):
            data = binfile.read(intsize)
            if data == '':
                break
            dest = struct.unpack('i',data)[0]
            print dest,
        print ''

    print 'totalnode = ',totalnode
    binfile.close()

def test(filename):
    totalnode = 0
    binfile = open(filename,'rb')
    intsize = struct.calcsize('i')

    while 1:
        data = binfile.read(intsize)
        if data == '':
            break
        src = struct.unpack('i',data)[0]

        print '>',src,
        totalnode += 1

        data = binfile.read(intsize)
        if data == '':
            break
        outdegree = struct.unpack('i',data)[0]
        print '|',outdegree

    binfile.close()

def genwebgraph(filename,no_src,max_outdegree):
    # src id | out degree | list of destination id 
    
    webgraph = open(filename,'wb')

    nodelist = random.sample(xrange(1,max_outdegree*10),max_outdegree*2)
    
    srclist = random.sample(nodelist,no_src)
    for srcid in srclist:

        # src id
        data = struct.pack('i',srcid)
        webgraph.write(data)
    
        # outdegree
        outdegree = random.randint(1,max_outdegree)
        data = struct.pack('i',outdegree)
        webgraph.write(data)

        # list of dest id
        for destid in random.sample(nodelist,outdegree):
            data = struct.pack('i',destid)
            webgraph.write(data)

if __name__ == '__main__' :
    # Fill in the parameters here
    filename = 'pick.webgraph'
    no_src = 10
    max_outdegree = 20
    printwg = 1

    genwebgraph(filename,no_src,max_outdegree)
    if printwg: printwebgraph(filename)
    test(filename)
